﻿using System;
using System.Threading;
using ChatClient.Handler;
using ChatCommon;
using Lidgren.Network;
using NetBrick.Client;

namespace ChatClient
{
    class ChatExampleClient : Client
    {
        private bool _connected;
        private readonly string _name;

        public ChatExampleClient(string name)
            : base("ChatExample")
        {
            _connected = false;
            _name = name;
        }

        protected override void Init()
        {
            Log.Init();
            DebugInfo("Initializing chat client...");
            new Thread(() =>
            {
                while (!Environment.HasShutdownStarted)
                {
                    if (!_connected) continue;
                    if(!EncryptionAvailable) continue;
                    var message = Console.ReadLine();
                    var chatPacket = CreatePacket(ChatPacketCode.ChatMessage);
                    chatPacket.read;
                    SendPacket(chatPacket, NetDeliveryMethod.ReliableOrdered);
                }
                Disconnect("User logged out.");
            }).Start();
            AddPacketHandler(ChatPacketCode.ChatMessage, new ChatPacketHandler(this));
            AddPacketHandler(ChatPacketCode.PlayerJoin, new PlayerJoinHandler(this));
            AddPacketHandler(ChatPacketCode.PlayerLeave, new PlayerLeaveHandler(this));
            DebugInfo("Initialized chat client.");
            DebugInfo("Connecting to the server...");
            Connect("localhost", 35565);
        }

        public override void DebugInfo(string message, params object[] arg)
        {
            Log.Info(message, arg);
        }

        public override void DebugWarn(string message, params object[] arg)
        {
            Log.Warn(message, arg);
        }

        public override void DebugError(string message, params object[] arg)
        {
            Log.Error(message, arg);
        }

        public override void DebugSevere(string message, params object[] arg)
        {
            Log.Severe(message, arg);
        }

        protected override void OnDisconnect(string reason)
        {
            if (_connected)
            {
                DebugInfo("Disconnected from the server. Reason: {0}", reason);
                _connected = false;
            }
            else
            {
                DebugError("Failed to connect to server. Reason: {0}", reason);
            }
        }

        protected override void OnConnect()
        {
            _connected = true;
            DebugInfo("Connected to the server.");
            var authPacket = CreatePacket(ChatPacketCode.Authenticate);
            authPacket.Write(_name);
            SendPacket(authPacket, NetDeliveryMethod.ReliableOrdered);
            EstablishEncryption();
        }
    }
}
